Skip to content

nexus: engine ask-bridge, dashboard activity, /session, and TUI fixes - #1

Merged
Darknode-Official merged 16 commits into
mainfrom
feat/engine-ask-bridge
Oct 25, 2026
Merged

Darknode-Official merged 16 commits into
mainfrom
feat/engine-ask-bridge

Conversation

@Darknode-Official

Copy link
Copy Markdown
Owner

What

Engine ask-bridge — every external engine's model can now raise the real terminal ask_user popup (not just the local Ollama loop), auto-wired with zero setup via an out-of-process MCP shim. Per-engine injection: claude --mcp-config, codex -c mcp_servers.*, opencode $OPENCODE_CONFIG, gemini $GEMINI_CLI_SYSTEM_SETTINGS_PATH (all merge, never replace the user's config).

Localhost dashboard — live Files changed, Tools used (proportional bars), and Uptime cards.

/session (alias /activity) — terminal view of uptime, turns, tokens, tools, and files changed.

Fixes

  • Composer scrolls to follow the caret up a tall draft (editing an earlier wrapped line no longer hides the text and cursor).
  • Async slash-command output (/agents, /race, /review, /fix, /dream, …) attaches to its own transcript block instead of cur(), so an intervening system message can't steal or hide it.
  • A held Backspace batch is no longer swallowed when a stray ESC report collides with it during a slow /restart.

Tests

Full suite green: 1325 / 177 / 199 / 16. Ask-bridge has 20+ tests incl. a real spawn-the-shim E2E; TUI fixes verified with a pty (pyte) harness.

Two input-handling bugs that surfaced as 'the caret jumps right and
backspace does nothing' (notably right after /restart, when the terminal
batches keystrokes buffered during the cold start):

- A held/batched Backspace arrives as one read ("\x7f\x7f…"). The keymap
  matches a single byte, and the printable guard let DEL (0x7f) through a
  naive 'seq >= " "' compare, so the run was INSERTED as stray chars
  instead of deleting. Replay a batched run of control bytes one at a time,
  and harden the composer's printable guard to never insert a control byte.
- A terminal report/arrow split across reads (lone ESC in one chunk, its
  body in the next) leaked the body into the composer as text. Reassemble a
  split escape sequence by briefly holding a lone trailing ESC.

Verified via pty harness (backspace, Alt+Backspace, batched arrows, split
reports) and 4 new composer unit tests. 1670 tests pass.
…for /clear

The ask card (Claude-Code 'pick one' prompt) now has three modes:
- pick-one   ask_user{question,options:[...]}            -> {selected,index}   (existing)
- pick-many  ask_user{question,options:[...],multi:true} -> {selected,indices} (checkboxes, Space toggles)
- free-text  ask_user{question,input:true}              -> {answer}           (type an answer)

renderAsk/askKey stay pure and snapshot-testable; the host carries the extra
picked/text state and resolves the matching shape. /clear now confirms through
a yes/no select card instead of the 'type /clear again' pattern, so the popup
is reachable on every engine (not just when the local model raises ask_user).

20 new ask unit tests + a pty end-to-end check of the /clear flow; 1690 pass.
…d MCP bridge

External engines run headless with their own toolset and cannot call Nexus's
in-process ask_user. A tiny clean-room MCP bridge closes the gap with zero user
setup: Nexus opens a local socket, the engine spawns a stdio MCP shim
(ask-mcp.js) that forwards an ask_user call back over the socket, and the TUI
shows the real popup (reusing renderAsk) and returns the answer.

Per-engine injection (one source of truth in the engine registry):
- claude: --mcp-config (live-verified via the pty harness)
- codex: repeatable -c mcp_servers.* overrides
- opencode: $OPENCODE_CONFIG -> a merged copy of the user's config (verified: opencode reports the nexus server connected)
- gemini: $GEMINI_CLI_SYSTEM_SETTINGS_PATH -> a {mcpServers} overrides file (gemini merges mcpServers across scopes, so only nexus is added)

User configs are never overwritten; only the reserved 'nexus' server is added.
New: lib/nexus/ask-bridge.js, ask-mcp.js, engine-mcp.js. +31 tests (1325 pass).
- dashboard: live Files changed, Tools used (proportional bars) and Uptime,
  fed by per-session file/tool/start accumulators in the turn-finish path
- /session (alias /activity): terminal view of uptime, turns, tokens, tools
  and files changed, registered in the command list
- fix: composer now scrolls to follow the caret up a tall draft (editing an
  earlier wrapped line no longer hides the text and the cursor)
- fix: async slash-command output (/agents, /race, /review, /fix, /dream, ...)
  now attaches to its own transcript block via ensureText(block) instead of
  cur(), so an intervening system message can't steal or hide the result
- fix: a held Backspace batch is no longer swallowed when a stray ESC report
  collides with it during a slow /restart (do not glue ESC onto a control run)
…orkflows

A new effort level above max, selectable from the /effort slider, "/effort
ultracode", or the autocomplete. On the claude engine it:
  - sends --effort max to the CLI (the highest thinking budget), and
  - prefixes each non-slash prompt with "ultracode: " so Claude Code opts its
    Workflow tool into standing orchestration mode, and
  - appends a short system directive making that opt-in explicit for the Nexus
    context (fan out, cover from independent angles, adversarially verify;
    solo only on trivial/conversational turns).

The level persists like any other effort setting and is capped by /budget.
Other (CLI) engines that take --effort map ultracode -> max; engines without
effort ignore it, same as the existing levels.
…nder)

The prompt box felt glitchy and laggy after /restart. Cause: bodyLines()
re-wraps the ENTIRE transcript (ANSI wrapping, diffs, tool cards) on every
paint — O(transcript) — and every keystroke paints synchronously. /restart
relaunches with --resume, which reloads the whole session, so the transcript
is large and each held-key repeat paid a full rebuild: visible input lag and
stutter.

Memoize the rendered transcript while idle. Typing never changes the
transcript, so when !busy we reuse the cached lines and only the composer
repaints; a burst of key-repeats now does one build, not one per key. The
cache is keyed on everything bodyLines reads (transcript length + last
message's text/tool-item signature, cols, expanded, effort, engine, model,
guard, branch, live MCP count, welcome tip, queued prompts) and is bypassed
entirely while busy or compacting so streaming text, spinners and running-tool
timers stay live. Not tied to /restart — any long session benefits.
wordHi() word-level diff highlighting called wordFlags(a, b, Infinity), so the
O(n*m) LCS table was never bounded. A single long changed line — a minified JS
line, a long JSON blob, a packed data row — produces tens of thousands of
tokens, and the n*m table then blows up: ~2s at 6k tokens/line, ~30s+ for a
~50KB minified line, all synchronous inside render(). Editing such a file (its
diff renders in the transcript and the /undo preview) froze the whole TUI.

Bound the LCS to 600 tokens/side (wordFlags already supports a cap and returns
null past it) and fall back to showing the line plainly when exceeded — the
diff is still correct, just without intra-line word emphasis on that one line.
Short lines are unaffected and keep full word-level highlighting. Measured:
6000 tokens/line 2187ms -> 1ms; 20000 tokens 30s+ -> 4ms.
…bsites

/api/state and /api/stream sent Access-Control-Allow-Origin: *. Binding to
127.0.0.1 keeps other machines out but not the user's own browser, so any
website they had open could fetch http://127.0.0.1:7979/api/state and read the
live session: prompts/activity, working dir, changed files, background-job
commands. With no Host check it was also reachable via DNS rebinding.

The dashboard page is same-origin, so it needs no CORS: drop the header,
answer only requests whose Host is this loopback port (127.0.0.1 or
localhost), and refuse a foreign Origin with 403.
ansiWrap() charged every glyph one column, but a surrogate-pair character
(emoji) is two columns on screen, and visLen/padRight and the scroll-rail
layout count it as two. Any reply or file snippet containing emoji wrapped
past its width budget and spilled over the right border: ansiWrap of six
emoji at width 4 produced a first row 8 columns wide.

Charge each glyph its visLen width (ch.length, 2 for a surrogate pair), and
always take at least one glyph per row so a glyph wider than the budget can't
stall the loop. All-BMP text wraps identically to before.
…explicit Submit)

The ask panel is now a rounded, bordered box matching the selection look:
an accent dot on the question, a numbered option list with a cursor, a
"Type a different answer" row that drops into a free-text field, and an
explicit Submit row so you confirm by selecting Submit rather than trusting
a bare Enter. Multi-select renders checkboxes and Submit returns the whole
set. ask.js stays a pure renderer+reducer; darknode.js wires the typing
transition and typed-answer routing through the single, multi, and bridge
handlers.
…-Code style)

A live list of sub-agents now sits under the prompt bar: each spawned agent
(via /agents, the spawn_agents tool, or a Claude-engine Task) shows its task,
a status glyph and elapsed time. Arrow-down from an empty composer drops focus
into the panel; from there ↑↓ move, enter opens an agent to read its full
output in a scrollable overlay, s stops a running agent, x clears the finished
ones, and esc returns to the composer. Finished agents stay listed with a
done / failed / stopped badge.

New pure, unit-tested module lib/cli/agents.js (renderer + reducer, 38 tests).
runSubagents gains per-agent controllers so a single agent can be stopped
without killing the rest of the turn.
Give the three surfaces their own identity instead of mirroring other CLIs
(the prompt bar is unchanged):

- Question card: a tab-headed card on a magenta rail ("◆ nexus asks" /
  "pick any" / "your answer"), [n] keycaps, a ▸ pointer, ■/□ checkboxes,
  a "write my own answer" row and a real [ Submit ] button that counts picks.
- Agents: a tree of lanes (├─ └─) under a "⟡ agents" header; running lanes
  animate a quarter-moon spinner and a bouncing ▰▱ activity meter, leader
  dots align a fixed status column (done / failed / stopped), the focused
  lane gets a ▶ cursor, and the hint shortens instead of being cut off on
  narrow terminals. The transcript overlay uses the same rail.
- Compaction: a new pure "condenser" (lib/cli/compact-anim.js) — the
  conversation drawn as a bar squeezed from both ends into a ◆ core, looping,
  with elapsed / tokens / folded size; it finishes as the closed frame
  "▸◆◂ condensed N tokens of conversation" in the transcript.

All pure and unit-tested (+20 tests).
Two new commands, both over real per-turn data captured at turn end (no
prompt text kept beyond a short label; never persisted):

- /turns (alias /ledger): a per-session cost ledger — one row per turn with
  tokens, cost and duration, the priciest turn flagged, session totals in the
  header. /turns <n> lists the last n.
- /cheaper: a cost advisor that only ever suggests LOSSLESS savings (turn the
  exact-repeat cache on, note verbatim repeats, explain claude prompt-caching,
  /compact a full context). The one quality tradeoff — effort — is flagged as
  such and never auto-applied; /cheap is untouched and stays lossless-only.

Pure, unit-tested module lib/cli/ledger.js (+23 tests). Per-turn capture reuses
the deltas the turn summary already computes; adds a cache-read baseline to the
turn stat so the cache-read delta is per-turn.
Three more commands:

- /tokens <file|dir>…  prices what @-attaching those paths would cost per turn
  BEFORE you send — walks dirs (skipping .git/node_modules/.nexus/etc),
  skips binaries + oversize files, ranks the heaviest files with their share,
  and shows first-turn vs cached-resend cost at the current model's rate. A
  lossless cost saver: see the bill before you pay it. New pure module
  lib/cli/tokcount.js (+17 tests); counts are a labelled estimate (~chars/4).
- /alias <name> = <text|/command>  persisted shortcuts (saved to settings,
  loaded at startup); /alias lists, /alias rm removes. The rest of the line is
  appended (or $ARGUMENTS substituted). Refuses to shadow a built-in.
- /retry  re-runs your last prompt fresh, bypassing the exact-repeat cache for
  that one send (a new one-shot bypassCacheOnce flag).

1434 run.js tests green.
@Darknode-Official
Darknode-Official merged commit 9b2a6f6 into main Oct 25, 2026
6 checks passed
Darknode-Official added a commit that referenced this pull request Oct 25, 2026
… dev server

- run_background spawns in its own process group; stop_background / exit kill the
  group. Before, only the sh wrapper died: npm run dev -> node kept running and kept
  the port. SIGHUP (terminal closed) now also stops jobs.
- job ids: '1', 1, '#1', 'job 1' resolve to bg1 (models rarely echo the prefix; stop
  with '1' used to report ok:false and leave the server up); no id + one running job
  = that job; unknown ids list the session's jobs; stop says whether it had already
  exited
- http_fetch may reach localhost ONLY when the listener is one of this session's
  background jobs (or its descendant) — start server, wait_for, fetch it works; every
  other local/private/metadata address stays blocked
Darknode-Official added a commit that referenced this pull request Oct 28, 2026
… engine gaps it found.

eval/edit-fixtures.js pairs files with edits written the way models get them slightly wrong (lost indentation, tabs vs spaces, CRLF, extra blank lines, copied line numbers, curly quotes, drifted patch line numbers, identical blocks) and the one right outcome for each: the exact resulting file, or a refusal that leaves the file alone. It reports correct / refused / corrupted per category; the test run requires every case correct. It scores the engine's tolerance, not a model's real-world apply rate.

On the previous engine: 30/35 correct, 4 refused, 1 corrupted. Now 35/35.
- Corruption: a whitespace-flexible match drops blank lines at the edges of the find but kept them in the replacement, so a find of "\n    return s\n\n" replaced with "\n    return t\n" wrote stray blank lines into the file. The replacement now loses the same edge blank lines.
- A find copied from search output with line-number prefixes ("2:  const url = ...", consecutive numbers on every line) now matches without them; the prefixes are dropped from the replacement too when it carries them. Non-consecutive numbers are not treated as prefixes.
- Curly quotes, dashes and nbsp in a find now match a file that has none, and are straightened in the replacement too. A file that uses curly quotes itself is left to the normal match.
- Either way the result tells the model what was dropped, so it can check the lines.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant